import { useMemo } from 'react';

import useWorkflow from '@/hooks/use-workflow';
import { WorkflowCheckListNodeResultType, WorkflowCheckListType } from '@/types/workflow/node';

import EmptyTip from '../EmptyTip';
import { SvgIcon } from '../icon';
import AvatarDisplay from '../work-modal/components/AvatarDisplay';

const CheckItem = ({ node }: { node: WorkflowCheckListNodeResultType }) => {
  const { moveToNode } = useWorkflow();

  return (
    <div
      className="min-w-[300px] max-w-[400px] cursor-pointer rounded-md border border-bg-1 bg-white shadow-sm hover:scale-[101%] hover:bg-primary-800/30"
      onClick={() => {
        moveToNode(node.nodeId);
      }}
    >
      <div className="flex items-center gap-2 bg-bg-1 p-3">
        <AvatarDisplay
          src={node.avatar}
          className="h-[20px] max-h-[20px] w-[20px] max-w-[20px]"
          size={30}
        />{' '}
        <span className="text-sm font-font-weight-400 text-text-5">{node.nodeName}</span>
      </div>
      <div className="flex flex-col gap-2 p-2">
        {node.checkResults
          .filter((check) => !check.isValid)
          .map((check) => {
            return (
              <div key={check.type} className="flex items-center gap-2">
                <div className="-mt-[3px] self-start">
                  <SvgIcon size={14} icon="warning" color="var(--warning-color)" />
                </div>
                <div className="flex items-center justify-center">
                  <span className="text-xs font-font-weight-400 text-text-4">{check.message}</span>
                </div>
              </div>
            );
          })}
      </div>
    </div>
  );
};

const WorkflowCheckList = ({ checkList }: { checkList: WorkflowCheckListType | undefined }) => {
  const errorNode: WorkflowCheckListNodeResultType[] = useMemo(() => {
    return checkList?.nodeResults.filter((node) => !node.isValid) || [];
  }, [checkList]);

  return (
    <div className="flex flex-col gap-2 pb-1">
      <div className="ml-2 text-base font-bold">检查清单({errorNode.length})</div>
      {errorNode.length > 0 ? (
        <div className="flex max-h-[400px] flex-col gap-3 overflow-y-auto px-1 py-2">
          {errorNode.map((node) => (
            <CheckItem key={node.nodeId} node={node} />
          ))}
        </div>
      ) : (
        <div className="p-4">
          <EmptyTip text="所有问题都已解决" />
        </div>
      )}
    </div>
  );
};

export default WorkflowCheckList;
